package kt.base

class SingletonClass private constructor(){

    // 懒汉式
    companion object{
        private var instance : SingletonClass? = null
        get(){
            if (null == field){
                field = SingletonClass()
            }
            return field
        }

        //这里不用getInstance作为为方法名，是因为在伴生对象声明时，内部已有getInstance方法，所以只能取其他名字
        @Synchronized
        fun getInstanceClass() : SingletonClass{
            return instance!!
        }
    }

}

//   双重校验锁式 使用lazy方式
class SingletonDemo private constructor(){
    companion object{
        val instance : SingletonDemo by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED){
            SingletonDemo()
        }
    }
}

// 静态内部类单例模式
class SingleStaticDemo private constructor(){
    companion object {
        val instance = SingletonHolder.holder
    }

    private object SingletonHolder {
        val holder= SingleStaticDemo()
    }
}




fun main() {
    var singleClass = SingletonClass.getInstanceClass()

    var singleDemo = SingletonDemo.instance


}





